<?php
class AddPhoneForm extends CFormModel
{
	public $areaCode;
	public $prefixCode;
	public $phoneNumber;
	
	public $phone;
	
	public function rules()
	{
		return array(
			// username and password are required
			array('areaCode, prefixCode, phoneNumber', 'required'),
			array('areaCode, prefixCode', 'length', 'is' => 3),
			array('phoneNumber', 'length', 'is' => 4),
			array('areacode, prefixcode, phonenumber', 'uniquePhone', 'areaCode', 'prefixCode', 'phoneNumber'),
		);
	}
	
	/**
	 * Because the function addAniToSubscriver error.
	 * So I must use updateAniSubscriber
	 * 
	 */
	public function save()
	{
		
		//sẻ lấy tất cả số điện thoại hiện tại sử dụng hàm 
		$subscriber_id = Yii::app()->user->getState('accountNumber');
		$objectResponce = EnticeWS::getANISubscriber($subscriber_id);
		
		//info
		$listInfo = array();
		$listInfo['FIRST_NAME'] = (string)$objectResponce->data->row->FIRST_NAME;
		$listInfo['LAST_NAME'] = (string)$objectResponce->data->row->LAST_NAME;
		$listInfo['ACCT_ID'] = (string)$objectResponce->data->row->ACCT_ID;
		$listInfo['CUST_ID'] = (string)$objectResponce->data->row->CUST_ID;
		$listInfo['STATUS'] = (string)$objectResponce->data->row->STATUS;
		$listInfo['PHONE'] = array();
		
		
		foreach($objectResponce->data->row->endpoint as $e)
		{
			$tmp = new stdClass();
			$tmp->VALUE = $e->VALUE;
			$tmp->CARD_PIN = $e->CARD_PIN;
			
			$listInfo['PHONE'][] = $tmp;
		}
		$tmp = new stdClass();
		$tmp->VALUE = trim($this->areaCode).trim($this->prefixCode).trim($this->phoneNumber);
		$tmp->CARD_PIN = CGlobal::$wsPinDefault;
		$listInfo['PHONE'][] = $tmp;
		

		$responce = EnticeWS::updateANISubscriber($subscriber_id, $listInfo);

		if($responce->returnStatus == 0 || $responce->returnStatus == 1)
		{
			return true;
		}
		else
		{
			throw new Exception("Update data by webservice fail: ".$responce['errorMessage']);
			return false;
		}
	}

	public function delete($phone)
	{
		$subscriber_id = Yii::app()->user->getState('accountNumber');
		
		$responce = EnticeWS::deleteANIfromSubscriber($subscriber_id, $phone);
		
		//var_dump($responce); die;
		
		if($responce->returnStatus == 0 || $responce->returnStatus == 1)
		{
			return true;
		}
		else
		{

			return false;
		}
	}
	
	
	/**
	 * Unique number.
	 *
	 * @return returnType returnDescription
	 */
	public function uniquePhone($attribute, $params) {
		if(!$this->hasErrors('Phone Unique'))
		{
			$valid = true;
			
			$phone = '';
			foreach($params as $i => $p)
			$phone .= $this->$p;
				
			if(TblCustomerCSIRelation::isPhoneExists($phone))
			$valid = false;
				
			if($valid === false)
			if(!$this->hasErrors('Phone Unique'))
			$this->addError( 'Phone Unique', 'Phone Number must be unique' );
		}
	}
}